package com.xiliu.rocketmq.transaction;

import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xiliu
 * @description 事物处理
 * @date 2022/3/23
 */
public class TransactionListenerImpl implements TransactionListener{

    private static Map<String, LocalTransactionState> STATE_MAP = new HashMap<>();
    /**
     * 执行具体的业务逻辑
     **/
    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {
        try{
            // 模拟调用服务
            System.out.println("用户A账户减500元");
            Thread.sleep(500);

            // 模拟出现异常，返回回滚状态
            System.out.println(1/0);

            System.out.println("用户B账户加500元");
            Thread.sleep(500);

            STATE_MAP.put(message.getTransactionId(),LocalTransactionState.COMMIT_MESSAGE);
            // 二次提交确认
            return LocalTransactionState.COMMIT_MESSAGE;
        }catch (Exception e){
            e.printStackTrace();
        }
        STATE_MAP.put(message.getTransactionId(),LocalTransactionState.ROLLBACK_MESSAGE);
        // 回滚
        return LocalTransactionState.ROLLBACK_MESSAGE;
    }

    /**
     * 消息回查
     **/
    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        return STATE_MAP.get(messageExt.getTransactionId());
    }
}
